package com.zry.yard.presenter

import android.annotation.SuppressLint
import android.content.Intent
import android.support.v7.widget.AppCompatSpinner
import android.util.Log
import android.view.View
import android.widget.AdapterView
import com.tsy.sdk.myokhttp.response.RawResponseHandler
import com.zry.yard.R
import com.zry.yard.R.id.detailedAddressTV
import com.zry.yard.R.id.operationDescriptionTV
import com.zry.yard.adapter.AddImageAdapter
import com.zry.yard.adapter.BatchOPeraSpinnerAdapter
import com.zry.yard.animation.RecyclerViewUtilKt
import com.zry.yard.been.*
import com.zry.yard.retrofit.BaseApiRetrofit
import com.zry.yard.retrofit.HttpServer
import com.zry.yard.retrofit.ShowUserView
import com.zry.yard.ui.activity.TraceabilityCreateActivity
import com.zry.yard.ui.service.UpLoadImgService
import com.zry.yard.utils.ACacheUtil
import com.zry.yard.utils.ToastUtil
import com.zry.yard.utils.UIUtil
import com.zry.yard.view.DataTimeUtil
import com.zry.yard.view.address.AddressPickerPop
import kotlinx.android.synthetic.main.activity_traceability_create.*
import me.nereo.multi_image_selector.MultiImageSelector
import org.json.JSONObject
import retrofit2.http.Field
import java.util.*
import kotlin.collections.HashMap

class TraceabilityCreatePresenter(private val activity: TraceabilityCreateActivity) : ShowUserView {


    var addImageAdapter: AddImageAdapter? = null
    private var batchDetail: BatchDetail? = null
    //    private var provinceStr: String? = null
//    private var cityStr: String? = null
//    private var districtStr: String? = null
    private var OperaID: String? = null


    fun traceabilityHandlerClick(view: View) {
        when (view.id) {
            R.id.createTraceabilityBtn -> {
                //提交数据
                OperaID = UUID.randomUUID().toString()
                addDetailOperaInfo()
            }
            R.id.selectTimeTV, R.id.dateImg -> {
                getData()
            }
//            R.id.operatingPlaceTV, R.id.nextImg -> {
//                getAddress()
//            }
        }
    }

    private fun addDetailOperaInfo() {

//        if (activity.operatingPlaceTV.text.toString().trim().isEmpty()) {
//            return ToastUtil.toast(activity, "操作地点不能为空")
//        }
        if (activity.detailedAddressTV.text.toString().trim().isEmpty()) {
            return ToastUtil.toast(activity, "操作地址不能为空")
        }
        if (activity.operationDescriptionTV.text.toString().trim().isEmpty()) {
            return ToastUtil.toast(activity, "操作详情不能为空")
        }


        val params: HashMap<String, String> = hashMapOf()
        params["OperaID"] = OperaID!!
        params["DetailID"] = batchDetail!!.DetailID
        params["ModelID"] = activity.batchNextInfo!!.ModelID
        params["OperaName"] = activity.traceabilityOperatorTV.text.toString().trim()
        params["OperaDate"] = activity.selectTimeTV.text.toString().trim()
        params["Remark"] = activity.operationDescriptionTV.text.toString().trim()
//        params["ProvinceName"] = activity.provinceStrCode!!
//        params["CityName"] = activity.cityStrCode!!
//        params["AreaName"] = activity.districtStrCode!!
        params["Address"] = activity.detailedAddressTV.text.toString().trim()
        params["EnterpriseID"] = ACacheUtil().getLoginInfo().EntID
        params["CreateUserID"] = ACacheUtil().getLoginInfo().userid
        params["BatchID"] = activity.batchID!!


        BaseApiRetrofit().myOkHttp.post()
                .url(BaseApiRetrofit.BASE_URL + "AddDetailOperaInfo")
                .params(params)
                .tag(this)
                .enqueue(object : RawResponseHandler() {
                    override fun onSuccess(statusCode: Int, response: String?) {
                        val jsonObject = JSONObject(response)
                        if (jsonObject.getString("State") == "1") {
                            ToastUtil.toast(activity, "节点流程保存成功")
                            //提交图片
                            val intent = Intent(activity, UpLoadImgService::class.java)
                            intent.putStringArrayListExtra("addImgList", activity.imageList)
                            intent.putExtra("OperaID", OperaID!!)
                            activity.startService(intent)

                            activity.finish()
                        } else {
                            ToastUtil.toast(activity, jsonObject.getString("Message"))
                        }
                    }

                    override fun onFailure(statusCode: Int, error_msg: String?) {
                        Log.e("TAG", error_msg)
                    }
                })


//        HttpServer(this).addDetailOperaInfo(
//                OperaID!!,
//                batchDetail!!.DetailID,
//                activity.batchNextInfo!!.ModelID,
//                activity.traceabilityOperatorTV.text.toString().trim(),
//                activity.selectTimeTV.text.toString().trim(),
//                activity.operationDescriptionTV.text.toString().trim(),
//
//                provinceStrCode!!,
//                cityStrCode!!,
//                districtStrCode!!,
//                activity.detailedAddressTV.text.toString().trim(),
//                ACacheUtil().getLoginInfo().EntID,
//                ACacheUtil().getLoginInfo().userid,
//                activity.batchID!!,
//                activity
//        )
    }


    override fun toMainActivity(what: Int, data: Any) {
        when (what) {
            41 -> {
                Log.e("TAG", data.toString())
                val resultData = data as MsgResultBean
                if (resultData.State == "1") {
                    ToastUtil.toast(activity, "节点流程保存成功")
                    //提交图片
                    val intent = Intent(activity, UpLoadImgService::class.java)
                    intent.putExtra("addImgList", activity.imageList)
                    intent.putExtra("OperaID", OperaID!!)
                    activity.startService(intent)

                    activity.finish()
                } else {
                    ToastUtil.toast(activity, resultData.Message)
                }
            }
        }
    }


    fun initRecycler() {
        val width = (UIUtil.getScreenWidth(activity) - UIUtil.getWidgetWidth(activity.createTraceabilityFieldPhotoTV)) / 5

        val recyclerViewUtilKt = RecyclerViewUtilKt(activity, activity.createTraceabilityFieldPhoto)
        recyclerViewUtilKt.initTableRecyclerView(4, 5)
        addImageAdapter = AddImageAdapter(activity, R.layout.item_add_image, activity.imageList, width)
        recyclerViewUtilKt.setAdapter(addImageAdapter!!)
        addImageAdapter?.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.itemDeleteTV -> {
                    activity.imageList!!.removeAt(position)
                    addImageAdapter?.notifyDataSetChanged()
                }
                R.id.itemAddImage -> {
                    if (activity.imageList!!.size > 0) {
                        val itemString = activity.imageList!![position]
                        if (itemString == "默认图片") {
                            pickImage()
                        }
                    } else {
                        pickImage()
                    }
                }
            }
        }
    }

    private fun pickImage() {


        val imagePathList = activity.imageList!!.filterNot { it == "默认图片" }
        activity.imageList!!.removeAll(activity.imageList!!)
        activity.imageList!!.addAll(imagePathList)

        //使用相机
        //boolean showCamera = mShowCamera.getCheckedRadioButtonId() == R.id.show;
        //最大图片数量
        val maxNum = 9

        val selector = MultiImageSelector.create(activity)
        selector.showCamera(true)
        selector.count(maxNum)
//        //单选图片
//        selector.single()
        //多选图片
        selector.multi()

        selector.origin(activity.imageList!!)
        selector.start(activity, activity.REQUEST_IMAGE)
    }


    fun initOPeraSpinner(selectNodeSpinner: AppCompatSpinner) {
        val batchOPeraSpinnerAdapter = BatchOPeraSpinnerAdapter(activity, activity.batchNextInfo!!.DetailList)
        selectNodeSpinner.adapter = batchOPeraSpinnerAdapter
        spinnerItemSelect(selectNodeSpinner)
    }


    private fun spinnerItemSelect(appCompatSpinner: AppCompatSpinner) {
        appCompatSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(p0: AdapterView<*>?, view: View?, position: Int, p3: Long) {
                when (appCompatSpinner) {
                    activity.selectNodeSpinner -> {
                        batchDetail = activity.batchNextInfo!!.DetailList[position]
                    }
                }
            }

            override fun onNothingSelected(p0: AdapterView<*>?) = Unit
        }
    }


//    private fun getAddress() {
//        AddressPickerPop(activity, activity.operatingPlaceLinear).setListener(object : AddressPickerPop.AddressListener {
//            @SuppressLint("SetTextI18n")
//            override fun handleResult(address: String, province: String, city: String, district: String, provinceCode: String, cityCode: String, districtCode: String) {
//                provinceStr = province
//                cityStr = city
//                districtStr = district
//
//                activity.operatingPlaceTV.text = province + city + district
//                activity.detailedAddressTV.setText("")
//
//                activity.provinceStrCode = provinceCode
//                activity.cityStrCode = cityCode
//                activity.districtStrCode = districtCode
//
//                Log.e("locationCode", activity.provinceStrCode)
//                Log.e("locationCode", activity.cityStrCode)
//                Log.e("locationCode", activity.districtStrCode)
//            }
//        })
//    }

    private fun getData() {
        DataTimeUtil(activity).setListener(object : DataTimeUtil.DateListener {
            @SuppressLint("SetTextI18n")
            override fun handleResult(dateYear: String, dateMonth: String, dateDay: String) {
                activity.selectTimeTV.text = "$dateYear-$dateMonth-$dateDay"
            }
        })
    }
}